import plugin from '../../../lib/plugins/plugin.js';
import fs from 'fs';
import image from "../components/img.js";

const path=process.cwd()
const sjzy=path+'/plugins/sv-plugin/config/专业.txt'
const sjxq=path+'/plugins/sv-plugin/config/校区.txt'
// 使用 Promise 来处理异步读取
const readFilePromise = (filePath) => {
    return new Promise((resolve, reject) => {
        fs.readFile(filePath, 'utf-8', (err, data) => {
            if (err) {
                reject(err);
            } else {
                resolve(data.split('\n'));
            }
        });
    });
};

export class svschool extends plugin {
	constructor() {
		super({
			/** 功能名称 */
			name: '星露谷随机大学',
			/** 功能描述 */
			dsc: '调用Yunzai自带更新模块进行星露谷插件更新',
			/** https://oicqjs.github.io/oicq/#events */
			event: 'message',
			/** 优先级，数字越小等级越高 */
			priority: 6666666666666666,
			rule: [
				{
					/** 命令正则匹配 */
					reg: '^#?(星露谷|sv)(插件)?大学$',
					/** 执行方法 */
					fnc: 'school'
				}
			]
		});
	}
    async school(e) {
        let member = await Bot.getGroupMemberInfo(e.group_id, e.at ? e.at : e.user_id);
        try {
        const [zylines, xqlines] = await Promise.all([
            readFilePromise(sjzy),
            readFilePromise(sjxq)
        ]);
        let yz1 = await redis.get(`Yunzai:school${member.user_id}`);yz1 = JSON.parse(yz1);
        if(yz1 === 2){
            let zyname =await redis.get(`Yunzai:school${member.user_id}_zyname`); zyname = JSON.parse(zyname);
            let xqname =await redis.get(`Yunzai:school${member.user_id}_xqname`); xqname = JSON.parse(xqname);
            const username = member.nickname;//学生名
            const { img } = await image(e, 'school', 'school',{
                username,
                zyname,
                xqname
            });
            let msg = [
                `已获取过星露谷大学通知书了，请查收\n`,img]
            e.reply(msg,true)
            return true;
        }
        let yz = 2;
        const username = member.nickname;//学生名
        const zyname = zylines[Math.floor(Math.random() * zylines.length)];
        const xqname = xqlines[Math.floor(Math.random() * xqlines.length)];

        const { img } = await image(e, 'school', 'school',{
            username,
            zyname,
            xqname
        });
        let msg = [
            `录取星露谷大学通知书来啦！请查收\n`,img]
        e.reply(msg,true)
        redis.set(`Yunzai:school${member.user_id}`, JSON.stringify(yz));
        redis.set(`Yunzai:school${member.user_id}_zyname`, JSON.stringify(zyname));
        redis.set(`Yunzai:school${member.user_id}_xqname`, JSON.stringify(xqname));
        return true;
        } catch (err) {
            console.error('星露谷大学读取文件失败:', err);
            e.reply('无法获取所需信息，请联系主人反馈。');
        }
    }
}